<?php
// +----------------------------------------------------------------------
// | 云南喵云科技
// +----------------------------------------------------------------------
// | 官方网站: https://www.meoyun.com
// +----------------------------------------------------------------------
// | Author: 喵大大
// +----------------------------------------------------------------------
// | Email: mmteen@sina.com
// +----------------------------------------------------------------------
// | Date: 2021/10/29/029
// +----------------------------------------------------------------------
// | Time: 18:59
// +----------------------------------------------------------------------
namespace App;

use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Jwt\Exception;
use EasySwoole\Jwt\Jwt;

class JwtController extends Controller
{
    protected $jwtKey = "WVZFUkdLSEpJT1hXRUZOSkgyNDU2QDE/IQ=="; //jwt加密key

    /**
     *   生成token
     * @param $data
     * @return String|null
     */
    public function buildToken($data,$user = 'user'): ?String
    {
        $jwtObject = Jwt::getInstance()
            ->setSecretKey($this->jwtKey) // 秘钥
            ->publish();

        $jwtObject->setAlg('HMACSHA256'); // 加密方式
        $jwtObject->setAud($user); // 用户
        $jwtObject->setExp(time()+3600*24*7); // 过期时间
        $jwtObject->setIat(time()); // 发布时间
        $jwtObject->setIss('easyswoole'); // 发行人
        $jwtObject->setJti(md5(time())); // jwt id 用于标识该jwt
        $jwtObject->setNbf(time()); // 在此之前不可用
        $jwtObject->setSub('主题'); // 主题

        // 自定义数据
        $jwtObject->setData($data);

        // 最终生成的token
        $token = $jwtObject->__toString();

        return $token;
    }

    /**
     * @param $token
     * @throws Exception
     */
    public function checkToken($token)
    {

        $jwtObject = Jwt::getInstance()->setSecretKey($this->jwtKey)->decode($token);
        $status = $jwtObject->getStatus();

        switch ($status){

            case 1:
                return $jwtObject->getData();

            case  -1:
                $this->message(420,"token已失效");

            case  -2:
                $this->message(420,"token已过期");
        }
    }
}